﻿using Peer.Game;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Peer
{

    public static class GameExtensions
    {
        public static OnReceiveEvent ChangeReceive(Action<PeerStream, OperationRequest> func)
        {
            return (peer, request) =>
            {
                func?.Invoke(peer, new OperationRequest(request.GetBytes()));
                return request.CreateResponse().ToAsnyc();
            };
        }
        /// <summary>
        /// 发送指令
        /// </summary>
        /// <param name="peer"></param>
        /// <param name="operationCode">指令</param>
        /// <returns></returns>
        public static Task SendOperationAsync(this PeerStream peer, byte operationCode)
        {
            var response = new Operation(operationCode);
            return peer.SendAsync(response.Serialize());
        }
        /// <summary>
        /// 发送指令
        /// </summary>
        /// <param name="peer"></param>
        /// <param name="operationCode">指令</param>
        /// <param name="parameters"> 附带数据</param>
        /// <returns></returns>
        public static Task SendOperationAsync(this PeerStream peer, byte operationCode, Dictionary<byte, object> parameters)
        {
            var response = new Operation(operationCode, parameters);
            return peer.SendAsync(response.Serialize());
        }

        /// <summary>
        /// 查询数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="peer"></param>
        /// <param name="operationCode">指令</param>
        /// <returns></returns>
        public static async Task<T> GetDataAsync<T>(this PeerStream peer, byte operationCode)
        {
            var response = new Operation(operationCode);
            var bytes = await peer.SendWithResponseAsync(response.Serialize());
            return MTP.Serialize.MTPSerialize.Deserialize<T>(bytes);
        }
    }
}
